{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 使用LLMs进行生成"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "LLMs，即大语言模型，是文本生成背后的关键组成部分。简单来说，它们包含经过大规模预训练的transformer模型，用于根据给定的输入文本预测下一个词（或更准确地说，下一个`token`）。由于它们一次只预测一个`token`，因此除了调用模型之外，您需要执行更复杂的操作来生成新的句子——您需要进行自回归生成。\n",
    "\n",
    "自回归生成是在给定一些初始输入，通过迭代调用模型及其自身的生成输出来生成文本的推理过程。在🤗 Transformers中，这由[generate()](https://huggingface.co/docs/transformers/main/zh/main_classes/text_generation#transformers.GenerationMixin.generate)方法处理，所有具有生成能力的模型都可以使用该方法。\n",
    "\n",
    "本教程将向您展示如何：\n",
    "\n",
    "* 使用LLM生成文本\n",
    "* 避免常见的陷阱\n",
    "* 帮助您充分利用LLM下一步指导\n",
    "\n",
    "在开始之前，请确保已安装所有必要的库：\n",
    "\n",
    "\n",
    "```bash\n",
    "pip install transformers bitsandbytes>=0.39.0 -q\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 生成文本"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "一个用于[因果语言建模](https://huggingface.co/docs/transformers/main/zh/tasks/language_modeling)训练的语言模型，将文本`tokens`序列作为输入，并返回下一个`token`的概率分布。\n",
    "\n",
    "\n",
    "<!-- [GIF 1 -- FWD PASS] -->\n",
    "<figure class=\"image table text-center m-0 w-full\">\n",
    "    <video\n",
    "        style=\"max-width: 90%; margin: auto;\"\n",
    "        autoplay loop muted playsinline\n",
    "        src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/assisted-generation/gif_1_1080p.mov\"\n",
    "    ></video>\n",
    "    <figcaption>\"LLM的前向传递\"</figcaption>\n",
    "</figure>\n",
    "\n",
    "使用LLM进行自回归生成的一个关键方面是如何从这个概率分布中选择下一个`token`。这个步骤可以随意进行，只要最终得到下一个迭代的`token`。这意味着可以简单的从概率分布中选择最可能的`token`，也可以复杂的在对结果分布进行采样之前应用多种变换，这取决于你的需求。\n",
    "\n",
    "<!-- [GIF 2 -- TEXT GENERATION] -->\n",
    "<figure class=\"image table text-center m-0 w-full\">\n",
    "    <video\n",
    "        style=\"max-width: 90%; margin: auto;\"\n",
    "        autoplay loop muted playsinline\n",
    "        src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/assisted-generation/gif_2_1080p.mov\"\n",
    "    ></video>\n",
    "    <figcaption>\"自回归生成迭代地从概率分布中选择下一个token以生成文本\"</figcaption>\n",
    "</figure>\n",
    "\n",
    "上述过程是迭代重复的，直到达到某个停止条件。理想情况下，停止条件由模型决定，该模型应学会在何时输出一个结束序列（`EOS`）标记。如果不是这种情况，生成将在达到某个预定义的最大长度时停止。\n",
    "\n",
    "正确设置`token`选择步骤和停止条件对于让你的模型按照预期的方式执行任务至关重要。这就是为什么我们为每个模型都有一个[~generation.GenerationConfig]文件，它包含一个效果不错的默认生成参数配置，并与您模型一起加载。\n",
    "\n",
    "让我们谈谈代码！\n",
    "\n",
    "<Tip>\n",
    "\n",
    "如果您对基本的LLM使用感兴趣，我们高级的[`Pipeline`](https://huggingface.co/docs/transformers/main/zh/pipeline_tutorial)接口是一个很好的起点。然而，LLMs通常需要像`quantization`和`token选择步骤的精细控制`等高级功能，这最好通过[generate()](https://huggingface.co/docs/transformers/main/zh/main_classes/text_generation#transformers.GenerationMixin.generate)来完成。使用LLM进行自回归生成也是资源密集型的操作，应该在GPU上执行以获得足够的吞吐量。\n",
    "\n",
    "</Tip>\n",
    "\n",
    "首先，您需要加载模型。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import AutoModelForCausalLM, BitsAndBytesConfig\n",
    "\n",
    "model = AutoModelForCausalLM.from_pretrained(\n",
    "    \"mistralai/Mistral-7B-v0.1\", device_map=\"auto\", quantization_config=BitsAndBytesConfig(load_in_4bit=True)\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "您将会注意到在`from_pretrained`调用中的两个标志：\n",
    "\n",
    "- `device_map`确保模型被移动到您的GPU(s)上\n",
    "- `load_in_4bit`应用[4位动态量化](https://huggingface.co/docs/transformers/main/zh/main_classes/quantization)来极大地减少资源需求\n",
    "\n",
    "还有其他方式来初始化一个模型，但这是一个开始使用LLM很好的起点。\n",
    "\n",
    "接下来，你需要使用一个[tokenizer](https://huggingface.co/docs/transformers/main/zh/tokenizer_summary)来预处理你的文本输入。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import AutoTokenizer\n",
    "\n",
    "tokenizer = AutoTokenizer.from_pretrained(\"mistralai/Mistral-7B-v0.1\", padding_side=\"left\")\n",
    "model_inputs = tokenizer([\"A list of colors: red, blue\"], return_tensors=\"pt\").to(model.device)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`model_inputs`变量保存着分词后的文本输入以及注意力掩码。尽管[generate()](https://huggingface.co/docs/transformers/main/zh/main_classes/text_generation#transformers.GenerationMixin.generate)在未传递注意力掩码时会尽其所能推断出注意力掩码，但建议尽可能传递它以获得最佳结果。\n",
    "\n",
    "在对输入进行分词后，可以调用[generate()](https://huggingface.co/docs/transformers/main/zh/main_classes/text_generation#transformers.GenerationMixin.generate)方法来返回生成的`tokens`。生成的`tokens`应该在打印之前转换为文本。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'A list of colors: red, blue, green, yellow, orange, purple, pink,'"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "generated_ids = model.generate(**model_inputs)\n",
    "tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "最后，您不需要一次处理一个序列！您可以批量输入，这将在小延迟和低内存成本下显著提高吞吐量。您只需要确保正确地填充您的输入（详见下文）。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['A list of colors: red, blue, green, yellow, orange, purple, pink,',\n",
       "'Portugal is a country in southwestern Europe, on the Iber']"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tokenizer.pad_token = tokenizer.eos_token  # Most LLMs don't have a pad token by default\n",
    "model_inputs = tokenizer(\n",
    "    [\"A list of colors: red, blue\", \"Portugal is\"], return_tensors=\"pt\", padding=True\n",
    ").to(model.device)\n",
    "generated_ids = model.generate(**model_inputs)\n",
    "tokenizer.batch_decode(generated_ids, skip_special_tokens=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "就是这样！在几行代码中，您就可以利用LLM的强大功能。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 常见陷阱"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "有许多[生成策略](https://huggingface.co/docs/transformers/main/zh/generation_strategies)，有时默认值可能不适合您的用例。如果您的输出与您期望的结果不匹配，我们已经创建了一个最常见的陷阱列表以及如何避免它们。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig\n",
    "\n",
    "tokenizer = AutoTokenizer.from_pretrained(\"mistralai/Mistral-7B-v0.1\")\n",
    "tokenizer.pad_token = tokenizer.eos_token  # Most LLMs don't have a pad token by default\n",
    "model = AutoModelForCausalLM.from_pretrained(\n",
    "    \"mistralai/Mistral-7B-v0.1\", device_map=\"auto\", quantization_config=BitsAndBytesConfig(load_in_4bit=True)\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 生成的输出太短/太长"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果在[GenerationConfig](https://huggingface.co/docs/transformers/main/zh/main_classes/text_generation#transformers.GenerationConfig)文件中没有指定，`generate`默认返回20个tokens。我们强烈建议在您的`generate`调用中手动设置`max_new_tokens`以控制它可以返回的最大新tokens数量。请注意，LLMs（更准确地说，仅[解码器模型](https://huggingface.co/learn/nlp-course/chapter1/6?fw=pt)）也将输入提示作为输出的一部分返回。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'A sequence of numbers: 1, 2, 3, 4, 5'"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model_inputs = tokenizer([\"A sequence of numbers: 1, 2\"], return_tensors=\"pt\").to(model.device)\n",
    "\n",
    "# By default, the output will contain up to 20 tokens\n",
    "generated_ids = model.generate(**model_inputs)\n",
    "tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'A sequence of numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,'"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Setting `max_new_tokens` allows you to control the maximum length\n",
    "generated_ids = model.generate(**model_inputs, max_new_tokens=50)\n",
    "tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 错误的生成模式"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "默认情况下，除非在[GenerationConfig](https://huggingface.co/docs/transformers/main/zh/main_classes/text_generation#transformers.GenerationConfig)文件中指定，否则`generate`会在每个迭代中选择最可能的token（贪婪解码）。对于您的任务，这可能是不理想的；像聊天机器人或写作文章这样的创造性任务受益于采样。另一方面，像音频转录或翻译这样的基于输入的任务受益于贪婪解码。通过将`do_sample=True`启用采样，您可以在这篇[博客文章](https://huggingface.co/blog/how-to-generate)中了解更多关于这个话题的信息。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'I am a cat. I am a cat. I am a cat. I am a cat'"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Set seed or reproducibility -- you don't need this unless you want full reproducibility\n",
    "from transformers import set_seed\n",
    "set_seed(42)\n",
    "\n",
    "model_inputs = tokenizer([\"I am a cat.\"], return_tensors=\"pt\").to(model.device)\n",
    "\n",
    "# LLM + greedy decoding = repetitive, boring output\n",
    "generated_ids = model.generate(**model_inputs)\n",
    "tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'I am a cat.  Specifically, I am an indoor-only cat.  I'"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# With sampling, the output becomes more creative!\n",
    "generated_ids = model.generate(**model_inputs, do_sample=True)\n",
    "tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 错误的填充位置"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "LLMs是[仅解码器](https://huggingface.co/learn/nlp-course/chapter1/6?fw=pt)架构，意味着它们会持续迭代您的输入提示。如果您的输入长度不相同，则需要对它们进行填充。由于LLMs没有接受过从`pad tokens`继续训练，因此您的输入需要左填充。确保在生成时不要忘记传递注意力掩码！"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'1, 2, 33333333333'"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# The tokenizer initialized above has right-padding active by default: the 1st sequence,\n",
    "# which is shorter, has padding on the right side. Generation fails to capture the logic.\n",
    "model_inputs = tokenizer(\n",
    "    [\"1, 2, 3\", \"A, B, C, D, E\"], padding=True, return_tensors=\"pt\"\n",
    ").to(model.device)\n",
    "generated_ids = model.generate(**model_inputs)\n",
    "tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'1, 2, 3, 4, 5, 6,'"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# With left-padding, it works as expected!\n",
    "tokenizer = AutoTokenizer.from_pretrained(\"mistralai/Mistral-7B-v0.1\", padding_side=\"left\")\n",
    "tokenizer.pad_token = tokenizer.eos_token  # Most LLMs don't have a pad token by default\n",
    "model_inputs = tokenizer(\n",
    "    [\"1, 2, 3\", \"A, B, C, D, E\"], padding=True, return_tensors=\"pt\"\n",
    ").to(model.device)\n",
    "generated_ids = model.generate(**model_inputs)\n",
    "tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 错误的提示"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "一些模型和任务期望某种输入提示格式才能正常工作。当未应用此格式时，您将获得悄然的性能下降：模型能工作，但不如预期提示那样好。有关提示的更多信息，包括哪些模型和任务需要小心，可在[指南](https://huggingface.co/docs/transformers/main/zh/tasks/prompting)中找到。让我们看一个使用[聊天模板](https://huggingface.co/docs/transformers/main/zh/chat_templating)的聊天LLM示例："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"I'm not a thug, but i can tell you that a human cannot eat\""
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tokenizer = AutoTokenizer.from_pretrained(\"HuggingFaceH4/zephyr-7b-alpha\")\n",
    "model = AutoModelForCausalLM.from_pretrained(\n",
    "    \"HuggingFaceH4/zephyr-7b-alpha\", device_map=\"auto\", quantization_config=BitsAndBytesConfig(load_in_4bit=True)\n",
    ")\n",
    "set_seed(0)\n",
    "prompt = \"\"\"How many helicopters can a human eat in one sitting? Reply as a thug.\"\"\"\n",
    "model_inputs = tokenizer([prompt], return_tensors=\"pt\").to(model.device)\n",
    "input_length = model_inputs.input_ids.shape[1]\n",
    "generated_ids = model.generate(**model_inputs, max_new_tokens=20)\n",
    "print(tokenizer.batch_decode(generated_ids[:, input_length:], skip_special_tokens=True)[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'None, you thug. How bout you try to focus on more useful questions?'"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Oh no, it did not follow our instruction to reply as a thug! Let's see what happens when we write\n",
    "# a better prompt and use the right template for this model (through `tokenizer.apply_chat_template`)\n",
    "\n",
    "set_seed(0)\n",
    "messages = [\n",
    "    {\n",
    "        \"role\": \"system\",\n",
    "        \"content\": \"You are a friendly chatbot who always responds in the style of a thug\",\n",
    "    },\n",
    "    {\"role\": \"user\", \"content\": \"How many helicopters can a human eat in one sitting?\"},\n",
    "]\n",
    "model_inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors=\"pt\").to(model.device)\n",
    "input_length = model_inputs.shape[1]\n",
    "generated_ids = model.generate(model_inputs, do_sample=True, max_new_tokens=20)\n",
    "print(tokenizer.batch_decode(generated_ids[:, input_length:], skip_special_tokens=True)[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# As we can see, it followed a proper thug style 😎"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 更多资源"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "虽然自回归生成过程相对简单，但要充分利用LLM可能是一个具有挑战性的任务，因为很多组件复杂且密切关联。以下是帮助您深入了解LLM使用和理解的下一步："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 高级生成用法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1. [指南](https://huggingface.co/docs/transformers/main/zh/generation_strategies)，介绍如何控制不同的生成方法、如何设置生成配置文件以及如何进行输出流式传输；\n",
    "2. [指南](https://huggingface.co/docs/transformers/main/zh/chat_templating)，介绍聊天LLMs的提示模板；\n",
    "3. [指南](https://huggingface.co/docs/transformers/main/zh/tasks/prompting)，介绍如何充分利用提示设计；\n",
    "4. API参考文档，包括[GenerationConfig](https://huggingface.co/docs/transformers/main/zh/main_classes/text_generation#transformers.GenerationConfig)、[generate()](https://huggingface.co/docs/transformers/main/zh/main_classes/text_generation#transformers.GenerationMixin.generate)和[与生成相关的类](https://huggingface.co/docs/transformers/main/zh/internal/generation_utils)。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### LLM排行榜"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1. [Open LLM Leaderboard](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard), 侧重于开源模型的质量;\n",
    "2. [Open LLM-Perf Leaderboard](https://huggingface.co/spaces/optimum/llm-perf-leaderboard), 侧重于LLM的吞吐量."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 延迟、吞吐量和内存利用率"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1. [指南](https://huggingface.co/docs/transformers/main/zh/llm_tutorial_optimization),如何优化LLMs以提高速度和内存利用；\n",
    "2. [指南](https://huggingface.co/docs/transformers/main/zh/main_classes/quantization), 关于`quantization`，如bitsandbytes和autogptq的指南，教您如何大幅降低内存需求。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 相关库"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1. [`text-generation-inference`](https://github.com/huggingface/text-generation-inference), 一个面向生产的LLM服务器；\n",
    "2. [`optimum`](https://github.com/huggingface/optimum), 一个🤗 Transformers的扩展，优化特定硬件设备的性能"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 4
}
